//
//  ICTextView.m
//  ICome
//
//  Created by 席鹏飞 on 2016/11/14.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICTextView.h"
#import "ICHeaderFile.h"

@interface ICTextView()
/** UILabel */
@property (nonatomic, strong) UILabel *placeholderLabel;
@end

@implementation ICTextView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.alwaysBounceVertical = YES;
        self.textColor = [UIColor blackColor];
        [self addObserver];
    }
    return self;
}

- (void)dealloc {
    [self removeObserver];
}

- (void)addObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewTextDidChange) name:UITextViewTextDidChangeNotification object:nil];
}

- (void)removeObserver {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
}

/**
 *  监听有文字输入
 */
- (void)textViewTextDidChange {
    [self setPlaceholderTextShow];
    
    if ([self.tvDelegate respondsToSelector:@selector(textViewTextDidChange:)]) {
        [self.tvDelegate textViewTextDidChange:self];
    }
}

/**
 *  设置占位文字的显示
 */
- (void)setPlaceholderTextShow {
    self.placeholderLabel.hidden = self.hasText;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.placeholderLabel.frame = self.bounds;
    self.placeholderLabel.x = 6;
    self.placeholderLabel.y = -2;
}

- (void)setPlaceholder:(NSString *)placeholder {
    _placeholder = placeholder;
    self.placeholderLabel.text = placeholder;
    [self setNeedsLayout];
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor {
    _placeholderColor = placeholderColor;
    self.placeholderLabel.textColor = placeholderColor;
    [self setNeedsLayout];
}

- (void)setPlaceholderFont:(UIFont *)placeholderFont {
    _placeholderFont = placeholderFont;
    self.placeholderLabel.font = placeholderFont;
    [self setNeedsLayout];
}

- (void)setText:(NSString *)text {
    [super setText:text];
    [self setPlaceholderTextShow];
}

- (void)setAttributedText:(NSAttributedString *)attributedText {
    [super setAttributedText:attributedText];
    [self setPlaceholderTextShow];
}

#pragma mark - Getter

- (UILabel *)placeholderLabel {
    if (!_placeholderLabel) {
        _placeholderLabel = [[UILabel alloc] init];
        _placeholderLabel.font = ICFont(15.0 * Level);
        _placeholderLabel.textColor = [UIColor lightGrayColor];
        _placeholderLabel.numberOfLines = 1;
        [self addSubview:_placeholderLabel];
    }
    return _placeholderLabel;
}

@end
